package com.magiccompass.alipay.barcode.util;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.TreeMap;

public class UrlUtil {
	public static String replaceUrlSpace2RealSpace(String urlStr){
		return urlStr.replaceAll("%20", " ");
	}
	
	// From 2016-04-13 discuss with alipay. sign value also need url encode.
	/*
	public static String makeParameterMap2StringExceptSign(TreeMap<String,String> sortedParams){
		StringBuffer content = new StringBuffer();
        List<String> keys = new ArrayList<String>(sortedParams.keySet());
        Collections.sort(keys);
        for (int i = 0; i < keys.size(); i++) {
            String key = keys.get(i);
            String value = sortedParams.get(key);
            if (StringUtil.areNotEmpty(key, value)) {
            	if("sign".equals(key)){
                    content.append((i == 0 ? "" : "&") + key + "=" + value);
            	}else{
                    content.append((i == 0 ? "" : "&") + key + "=" + urlConvert(value,sortedParams.get("_input_charset")));
            	}
            }
        }
        return content.toString();
	}
	*/
	
	public static String makeParameterMap2String(TreeMap<String,String> sortedParams){
		StringBuffer content = new StringBuffer();
        List<String> keys = new ArrayList<String>(sortedParams.keySet());
        Collections.sort(keys);
        for (int i = 0; i < keys.size(); i++) {
            String key = keys.get(i);
            String value = sortedParams.get(key);
            if (StringUtil.areNotEmpty(key, value)) {
            	content.append((i == 0 ? "" : "&") + key + "=" + urlConvert(value,sortedParams.get("_input_charset")));
            }
        }
        return content.toString();
	}
	
	private static String urlConvert(String orgStr, String charset){
		String returnStr = null;
		try {
			returnStr = URLEncoder.encode(orgStr, charset);
		} catch (UnsupportedEncodingException e) {
			returnStr = orgStr;
			e.printStackTrace();
		}
		//returnStr = returnStr.replace("+", "%20");
		return returnStr;
	}
	
	public static void main(String[] args){
		String testStr = "PAYMENT TO MAGIC COMPASS";
		System.out.println(urlConvert(testStr,"UTF-8"));
		try {
			System.out.println(java.net.URLEncoder.encode("http://www.samplemerchant.com/notification", "UTF8").replace("+", "%20"));
			System.out.println(java.net.URLEncoder.encode(testStr, "UTF8").replace("+", "%20"));
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
